// pages/business_info/business_info.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util'), WeValidator = require('../../utils/we-validator'), QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js'), mapsdk = new QQMapWX({key: app.globalData.mapSdkKey});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user:{},
    industryCategories: [],
    step: 1,
    index: 0,
    logo: '',
    license_type: null,
    license_types: ['永久', '日期选择'],
    device_statusBarHeight: app.device_statusBarHeight + 'px',  //状态栏高度
    headerHeight: '',//设置main的padding-top,
    suggestion:[],
    cities:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //设置main的padding-top
    let that=this;
    var query = wx.createSelectorQuery();
    query.select('#header').boundingClientRect()
    query.exec(function (res) {
      that.setData({ headerHeight: res[0].height + 'px' })
    })

    // 结束设置main的padding-top
    core.get({
      url: '/xilujob.enterprise/info',
      success: ret => {
        let info = ret.data.enterprise_info, auditStatus = ret.data.audit_status;
        info.environment_images = info.environment_images ? info.environment_images.split(','):[];
        this.setData({
          user: ret.data.user,
          info: info,
          logo: info.logo,
          auditStatus: auditStatus,
        });
      }
    });

    util.getSiteCities().then(cities => {
      let city = [];
      for(let i=0;i<cities.length;i++){
        city.push({id:cities[i].city_id,name:cities[i].city_name})
      }
      this.setData({cities: city});
    });

    util.getCompanyTypes().then(types=>{
      this.setData({companyTypes: types});
    });
    util.getCompanyScales().then(scales=>{
      this.setData({companyScales: scales});
    })
    util.getIndustryCategories().then(items=>{
      this.setData({industryCategories: items});
    });
    this.setData({userinfo: app.getUserinfo(true)});
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  sure(e){
    let value = e.currentTarget.dataset.value;
    this.setData({['info.address']: value});
    this.setData({suggestion: []})
  },
  //公司地址
  bindCompanyname(){
    let page = this;
    //获取定位
    let lat = this.data.info.lat
    let lng = this.data.info.lng
    if(lat && lng){
      page.chooseAddr(lat,lng)
    }else{
      wx.getLocation({
        success: res => {
         page.chooseAddr(res.latitude,res.longitude)
        },
        fail: res => {
          page.setData({position:false});
        }
      });
    }
    
  },
  chooseAddr(lat,lng){
    let page = this;
    wx.chooseLocation({
      latitude: lat,
      longitude: lng,
      success:res2=>{
       console.log(res2);
       if(res2.errMsg=='chooseLocation:ok'){
        page.setData({['info.address']: res2.address,['info.lat']:res2.latitude,['info.lng']: res2.longitude});
       }else{
        wx.showToast({
          title: '选择失败',
          icon:'none'
        })
       }
        
      },
      fail:res2=>{
        // wx.showToast({
        //   title: '选择失败',
        //   icon:'none'
        // })
      }
    })
  },
  bindCityChange(event) {
    let selectedItem = event.detail.items[0];
    this.setData({'info.city_id': selectedItem.id});
  },
  bindIndustryCategoryChange(event) {
    let selectedItem = event.detail.items[0];
    this.setData({'info.industry_category_id': selectedItem.id});
  },
  uploadLogo() {
    wx.chooseImage({
      count: 1,
      success: res => {
        let file = res.tempFiles[0];
        core.uploadFile({
          filePath: file.path,
          success: (ret, response) => {
            this.setData({'info.logo': ret.data.url});
          }
        });
      }
    });
  },
  bindSubmit(event) {
    let data = event.detail.value, id = event.detail.target.dataset.id;
    console.log(data);
    let validator1 = {
      rules: {
        company_name: {required:true},
        industry_category_id: {required: true},
        company_type_id: {required:true},
        company_scale_id: {required:true},
        contact_person: {required:true},
        contact_phone: {required:true,mobile:true},
        contact_email: {email:true},
        address: {required:true},
        logo: {required:true},
        license_img: {required:true}
      },
      messages: {
        company_name: {required:'请输入企业名称'},
        industry_category_id: {required: '请选择所属行业'},
        company_type_id: {required:'请选择公司性质'},
        company_scale_id: {required:'请选择公司规模'},
        contact_person: {required:'请输入联系人'},
        contact_phone: {required:'请输入联系电话',mobile:'请输入正确的手机号'},
        contact_email: {email:'请输入正确的邮箱地址'},
        address: {required:'请输入公司地址'},
        logo: {required:'请上传Logo'},
        license_img: {required:'请上传营业执照'}
      }
    };
    validator1 = new WeValidator(validator1);
    if(id=='next') {
      if(!validator1.checkData(data)) {
        return;
      }
      this.setData({step:2});
      return;
    }else if(id==='submit1') {
      if(!validator1.checkData(data)) {
        return;
      }
    }else if(id==='submit2') {

    }

    // let keys = ['full_name','industry_category_id','contact_person','contact_phone','contact_email','address','logo',
    //   'company_scale_id','company_type_id','intro','environment_images','license_img','company_name','license_no','valid_date'];
    // let postData = {};
    // keys.forEach(key => postData[key] = this.data.info[key]);
    let benefitIds = [];
    this.data.info.benefits.forEach(item=>benefitIds.push(item.id));
    data.benefit_ids = benefitIds.join(',');
    data.intro = this.data.info.intro;
    data.environment_images = this.data.info.environment_images.length > 0 ? this.data.info.environment_images.join(',') : '';
    let userinfo = app.getUserinfo();
    data.lat = this.data.info.lat;
    data.lng = this.data.info.lng;
    core.post({
      url: 'xilujob.enterprise/audit', data: data,
      success: ret => {
        app.eventBus.emit(app.Events.UcenterInfoCompleteChange, ret.data.enterprise_info.info_complete);
        if(userinfo.group_model.audit_status=='0') {
          userinfo.group_model.audit_status = ret.data.audit_status;
          app.setUserinfo(userinfo);
          wx.redirectTo({url: '/pages/post/post'});
          wx.showToast({
            title: '尊敬的用户您已经进入审核阶段，选择继续发布职位或等待审核',icon:'none',duration:'2000'
          });
          return;
        }
        if(getCurrentPages().length===1) {
          wx.switchTab({url: '/pages/indexpage/indexpage'});
        }else {
          wx.navigateBack();
        }
      }
    });

  },

  // 认证信息相关操作
  uploadLicense() {
    // if(![0,3].includes(parseInt(this.data.audit_status)))
    //   return;
    let page = this;
    wx.chooseImage({
      count:1,
      success: res => {
        let file = res.tempFiles[0];
        if(file.size > 10*1024*1024) {
          wx.showToast({title:'文件大小最多10M',icon:'none'});
          return;
        }
        core.uploadFile({
          filePath: file.path,
          success(ret, response) {
            page.setData({'info.license_img': ret.data.url});
          }
        })
      }
    });
  },
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      'info.valid_date': e.detail.value,
    })
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    if(e.detail.value==0) {
      this.setData({'info.valid_date': '永久'});
    }else {
      this.setData({'info.valid_date': ''});
    }
    this.setData({
      license_type: e.detail.value,
    })
  },

  bindEditLabel() {
    wx.navigateTo({
      url: '/pages/show_label/show_label',
      events: {
        infoTransfer: data => {
          this.setData({['info.benefits']: data.info.benefits});
        }
      },
      success: res => {
        res.eventChannel.emit('infoTransfer', {info:this.data.info});
      }
    });
  },
  bindCompanyTypeChange(event) {
    let selectedCompanyType = event.detail.items[0];
    this.setData({'info.company_type_id': selectedCompanyType.id});
  },
  bindCompanyScaleChange(event) {
    let selectedCompanyScale = event.detail.items[0];
    this.setData({'info.company_scale_id': selectedCompanyScale.id});
  },
  bindEditIntro() {
    wx.navigateTo({
      url: '/pages/business_edit/business_edit',
      events: {
        infoTransfer: data => {
          this.setData({['info.intro']: data.info.intro});
        }
      },
      success: res => {
        res.eventChannel.emit('infoTransfer', {info:this.data.info});
      }
    });
  },
  bindEditEnvironmentImages() {
    wx.navigateTo({
      url: '/pages/environment/environment',
      events: {
        infoTransfer: data => {
          this.setData({['info.environment_images']: data.info.environment_images});
        }
      },
      success: res => {
        res.eventChannel.emit('infoTransfer', {info:this.data.info});
      }
    });
  },

  bindNext() {
    this.setData({step:2})
  },

  bindPrev() {
    this.setData({step:1})
  },

  preview() {
    let userinfo = app.getUserinfo();
    if(userinfo.group_id==2) {
      wx.navigateTo({
        url: '/pages/recruitment_homepage/recruitment_homepage?id='+this.data.info.company_id
      });
    }else if(userinfo.group_id==3) {
      wx.navigateTo({
        url: '/pages/recruitment_status/recruitment_status?id='+this.data.userinfo.id
      });
    }
  },

  input(e) {
    let name = e.currentTarget.dataset.name;
    this.setData({['info.'+name]: e.detail.value});
  },
  bindSwitchGroup() {
    wx.navigateTo({
      url: '/pages/change/change'
    });
  },
  bindBack() {
    let pages = getCurrentPages();
    if(pages.length===1) {
      wx.switchTab({
        url: '/pages/user_center/user_center'
      });
    }else {
      wx.navigateBack();
    }
  },

});
